import json

from django.db.models import Count
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt

from baobaoxiong.upload_down import upload_img, download
from parents.models import Parents, Growth
from schoolmaster.models import *
from baobaoxiong.yueling import *

# Create your views here.


# 老师绑定后的首页
@csrf_exempt
def index_views(request):
    uphone = request.POST.get('uphone')  # 获取家长电话
    user = Parents.objects.filter(uphone=uphone).first()
    student = user.student
    upload_img(str(student.photo))  # 上传图片到七牛云
    url = download(str(student.photo))
    results = student.test_results.all().order_by('-yueling')  # 降序排序
    lst = []
    if results:
        count = len(results)  # 统计有多少份报告
        for result in results:
            tup = fx(int(result.yueling))  # 获取年龄，月龄（2,5）
            if type(tup) is tuple:
                title = '%d岁%d月龄测评报告%03d' % (tup[0], tup[1], count)
            else:
                title = '%d岁测评报告%03d' % (tup, count)
            dic = {
                'title': title,  # 报告名称
                'score': result.score,  # 分数
                'rid': result.id,  # 测试结果id
            }
            lst.append(dic)
            count -= 1

        dic_data = {
            'uname': student.uname,  # 姓名
            'age': fn(student.birth)[2],  # 月龄
            'gender': student.gender,  # 性别
            'photo': url,  # 学生头像
            'sid': student.id,  # 学生id
            'data': lst,  # 报告结果
        }
        return JsonResponse(dic_data)
    else:
        dic_data = {
            'uname': student.uname,  # 姓名
            'age': fn(student.birth)[2],  # 月龄
            'gender': student.gender,  # 性别
            'photo': url,  # 学生头像
            'sid': student.id,  # 学生id
            'data': [],  # 报告结果
        }
        return JsonResponse(dic_data)


# 开始测评页
@csrf_exempt
def start_page_views(request):
    id = request.POST.get('sid')  # 获取学生id
    student = Student.objects.get(id=id)
    # 获取园所
    school = student.school
    upload_img(str(school.logo))  # 上传图片到七牛云
    url = download(str(school.logo))
    birth = student.birth
    # 计算年龄，月份，总月龄
    yue_ling = fn(birth)  # (23, 11, 287) 23年龄，11月份，287总月龄
    dic = {
        'name': student.uname,
        'age': "%s岁%s个月" % (str(yue_ling[0]), str(yue_ling[1])),
        'gender': student.gender,
        'schoollogo': url,
        'introduce': school.introduce
    }
    return JsonResponse(dic)


@csrf_exempt
def test_views(request):
    id = request.POST.get('sid')  # 获取学生id
    student = Student.objects.get(id=id)
    birth = student.birth
    moonage = fn(birth)
    if not Moonage.objects.filter(age=moonage[2]).exists():
        return JsonResponse({'status': 'failed', 'text': '没有该年龄的题'})
    school = student.school  # 获取园所
    powers = school.school_powers.all()

    l_powers = []
    for power in powers:
        # 获取月龄对应的能力线
        age = power.moonage_set.filter(age=moonage[2]).first()
        if age:
       #    l_powers.append(power)
            l_powers.append(age)
    # 获取测评题目
    l_tests = []
    for capacity in l_powers:
        tests = capacity.tests.filter(isDelete=False).all()
        if tests:
            for k in tests:
                l_tests.append(k)
    # 添加题和选项
    l_choices = []
    for chose in l_tests:
        choices = chose.question_choices.all()  # 获取测评题选项
        lst_option = []  # 添加每题的所有选项
        for question in choices:
            dic = {
                'id': question.id,  # 选项id
                'optionname': question.choiceName,  # 选项名
            }
            lst_option.append(dic)
        dic1 = {
            'title': chose.biaoti,  # 题名
            'option': lst_option,  # 该题选项
            }
        l_choices.append(dic1)  # 加进列表中
    dic2 = {
        'count': len(l_choices),  # 题的数量
        'data': l_choices,  # 标题，选项数据
        }
    return JsonResponse(dic2)


@csrf_exempt
def test_result_views(request):
    # 获取学生id
    sid = request.POST.get('sid')
    # 获取前端的选项 id
    ids = request.POST.get('ids')
    lst = json.loads(ids)

    student = Student.objects.get(id=sid)
    birth = student.birth
    yue_ling = fn(birth)
    age = yue_ling[2]
    # 保存数据到Testresult
    testresutl = Testresutl()
    testresutl.yueling = age
    testresutl.xuesheng = student
    testresutl.save()

    school = student.school
    # 园所对应能力线
    powers = school.school_powers.all()

    # 获取与月龄对应能力线的对象
    l_powers = []
    for power in powers:
        # 获取月龄对应的能力线
        moonage = power.moonage_set.filter(age=age).first()
        if moonage:
          # l_powers.append(power)
            l_powers.append(moonage)
    # 获取总分
    score = 0
    # 获取筛选出Test的数量
    i = 0
    # 获取测评结果Testresult对象
    obj = Testresutl.objects.filter(xuesheng_id=student.id, yueling=age).order_by('-id').first()
    for capacity in l_powers:
        # 保存数据到Testdetail中
        testdetail = Testdetail()

        able = capacity.abilities  # 月龄反向查找能力线
        testdetail.powername = able.powerTitle
        testdetail.testresult = obj
        testdetail.save()
        tests = capacity.tests.filter(isDelete=False).all()  # 获取能力线题
        if not tests:
            return JsonResponse({'status': 'failed'})
        grade = 0  # 计算能力线结果
        for k in tests:
            i = i + 1
            choices = k.question_choices.all()  # 获取每道题选项
            for ch in choices:
                leap = 0
                # 获取每道题选项得分
                for id in lst:
                    if ch.id == int(id):
                        score = score + ch.grade
                        grade = grade + ch.grade

                        # 保存数据到 Questionresult表中
                        questionresult = Questionresult()
                        # 获取测评详情Testdetail对象
                        chr = Testdetail.objects.filter(testresult_id=obj.id, powername=capacity.abilities.powerTitle).first()
                        questionresult.questionName = k.biaoti
                        questionresult.getscore = ch.grade
                        questionresult.testdetail = chr
                        questionresult.save()
                        leap = 1
                        break
                if leap:
                    break
        grade = grade / len(tests)
        result = ''
        if grade > 0 and grade < 1.5:
            result = '劣'
        elif (grade > 1.5 or grade == 1.5) and grade < 2.5:
            result = '差'
        elif (grade > 2.5 or grade == 2.5) and grade < 3.5:
            result = '中'
        elif (grade > 3.5 or grade == 3.5) and grade < 4.5:
            result = '良'
        elif (grade > 4.5 or grade == 4.5) and (grade < 5 or grade == 5):
            result = '优'
        # 保存结果 到Testdetail中
        obj2 = Testdetail.objects.filter(powername=capacity.abilities.powerTitle, testresult_id=obj.id).first()
        obj2.result = result
        obj2.save()
    # 计算总分
    score = int((score / (i * 5)) * 100)
    # 保存到 Testresult 中
    obj.score = score
    obj.save()

    lst_powers = []
    # 筛选对应能力线结果
    testpowers = Testdetail.objects.filter(testresult_id=obj.id)
    for power_result in testpowers:
        dic = {
            'powername': power_result.powername,  # 能力线名
            'result': power_result.result,  # 结果
        }
        lst_powers.append(dic)
    # 统计推荐视频数量
    vid_lst = []
    for power in testpowers:
        if power.result == '劣' or power.result == '差':
            # 计算能力线对应视频
            ability = Ability.objects.filter(powerTitle=power.powername, school_id=school.id).first()
            if ability:
               videos = ability.videos.filter(isDelete=False)
               if not videos:
                    return JsonResponse({'status': 'failed'})
               for video in videos:
                    # 计算视频对应月龄
                    if video.moonage_set.filter(age=age):
                        vid_lst.append(video.id)
    count = len(set(vid_lst))         
    upload_img(str(student.photo))  # 上传图片到七牛云
    url = download(str(student.photo))
    dic1 = {
        'name': student.uname,
        'photo': url,
        'age': age,
        'gender': student.gender,
        'score': obj.score,
        'count': count,  # 前端需要判定是否为0，为0，不推荐
        'data': lst_powers  # 能力线，结果
    }
    return JsonResponse(dic1)


@csrf_exempt
def push_video_views(request):
    sid = request.POST.get('sid')  # 获取学生姓名
    student = Student.objects.get(id=sid)
    school = student.school
    birth = student.birth
    yue_ling = fn(birth)
    age = yue_ling[2]
    # 获取测评结果Testresult对象
    obj = Testresutl.objects.filter(xuesheng_id=student.id, yueling=age).order_by('-id').first()
    # 筛选对应能力线结果
    testpowers = Testdetail.objects.filter(testresult_id=obj.id).all()
    l_powers = []
    for power in testpowers:
        if power.result == '劣' or power.result == '差':
            l_powers.append(power)

    vid_lst = []
    for capacity in l_powers:
        ability = Ability.objects.filter(powerTitle=capacity.powername, school_id=school.id).first()
        if ability:
            # for able in ability:
            videos = ability.videos.filter(isDelete=False)
            if not videos:
                    return JsonResponse({'status': 'failed'})
            # video = ability.video
            for video in videos:
                if video.moonage_set.filter(age=age):
                    # 获取视频对应的能力
                    vid_lst.append(video.id)

    # 添加视频信息
    lst = []
    count = 0
    for k in set(vid_lst):
        video = Video.objects.get(id=k)
        abilitynames = video.abilities.all()
        lst_power = []
        for i in abilitynames:
            lst_power.append(i.powerTitle)  # 获取对应能力线名称

        # 获取视频点赞，分享数量
        # commend = video.commend
        # 视频评论数
        # reviews = video.review_set.all().aggregate(count=Count('id'))
        dic = {
            'count': count,
            'vid': video.id,  # 视频id
            'title': video.title,  # 视频标题
            'url': video.site,  # 视频地址
            # 'like': commend.like,  # 视频点赞数
            # 'reviews': reviews['count'],  # 视频评论数
            # 'share': commend.share,  # 视频分享数
            'power': lst_power,  # 视频对应能力
            'style': 'display:block',
        }
        lst.append(dic)
        count += 1
    dic1 = {
        # 'pid': pid,  # 家长id
        'data': lst,  # 视频信息，[{},{}]
    }
    return JsonResponse(dic1)
@csrf_exempt
def bring_up_views(request):
    gender = request.POST.get('gender')  # 获取性别
    age = request.POST.get('age')  # 获取月龄
    sex = ''
    if gender == '男':
        sex = 2
    elif gender == '女':
        sex = 3
    growth = Growth.objects.filter(gender=sex, monthage=age, isDelete=False).first()
    if growth:
        upload_img(str(growth.picture))  # 上传图片到七牛云
        url = download(str(growth.picture))
        dic = {
            'img': url,  # 养育图片
        }
        return JsonResponse(dic)
    else:
        return JsonResponse({'status': 'failed'})

# 视频点赞
@csrf_exempt
def like_views(request):
    # 1:成功点赞
    # 0:取消点赞
    status = request.POST.get('status')
    id = request.POST.get('vid')
    video = Video.objects.filter(id=id).first()
    commend = video.commend
    if int(status):
        commend.like = commend.like - 1
        commend.save()
    else:
        commend.like = commend.like + 1
        commend.save()

    dic = {
        'count': commend.like,
    }
    return JsonResponse(dic)


# 视频分享
# def share_views(request):
#     pass
#
#
# # 视频评论
# def comment_views(request):
#     pass



